using System.Threading;
using System.Threading.Tasks;
using UnityEngine;

namespace EntityKit.Runtime
{
    public static partial class AudioKit
    {
        public static float SingleVolume
        {
            get => singleVolume;
            set
            {
                if (singleSource != null) singleSource.volume = singleVolume = Mathf.Clamp01(value);
            }
        }

        /// <summary>
        /// 单声道音效是否正在播放
        /// </summary>
        public static bool IsSinglePlaying => singleSource != null && singleSource.isPlaying;


        public static bool SingleMute
        {
            get => isSingleMute;
            set
            {
                if (isSingleMute == value) return;
                isSingleMute = value;
                if (singleSource != null) singleSource.mute = value;
            }
        }

        /// <summary>
        /// 播放单声道音效
        /// </summary>
        /// <param name="clip">音频剪辑</param>
        /// <param name="isLoop">是否循环</param>
        /// <param name="speed">播放速度</param>
        public static void PlaySingleSound(AudioClip clip, bool isLoop = false, float speed = 1)
        {
            if (!isInitialized || !ValidateClip(clip)) return;

            ConfigureAudioSource(singleSource, clip, isLoop, speed);
            if (singleSource != null)
            {
                singleSource.Play();
            }
        }

        /// <summary>
        /// 停止单声道音效
        /// </summary>
        public static void StopSingleSound()
        {
            if (singleSource != null)
            {
                singleSource.Stop();
            }
        }

        /// <summary>
        /// 暂停单声道音效
        /// </summary>
        public static void PauseSingleSound()
        {
            if (singleSource != null)
            {
                singleSource.Pause();
            }
        }


        /// <summary>
        /// 恢复单声道音效
        /// </summary>
        public static void ResumeSingleSound()
        {
            if (singleSource != null)
            {
                singleSource.UnPause();
            }
        }

        private static void SingleSoundInitialize()
        {
            singleSource = CreateAudioSource("SingleSource", singleVolume, 1, 0, root, isSingleMute);
            if (singleSource != null)
            {
                SingleVolume = singleVolumeDefault;
            }
        }

        private static void SingleSoundUpdate()
        {
        }

        private static void SingleSoundRelease()
        {
            if (singleSource != null)
            {
                Object.Destroy(singleSource.gameObject);
                singleSource = null;
            }
        }


        private static AudioSource singleSource;

        private static float singleVolumeDefault = 1;

        private static float singleVolume;

        private static bool isSingleMute;
    }
}